import {defineComponent, inject, watch} from 'vue';
import './index.scss';
import {FormItemContext, FormItemKey} from "../Form/types";

export default defineComponent({
  name: 'Field',
  props: {
    modelValue: {
      type: [String, Number],
      default: ''
    },
    type: {
      type: String,
      default: 'text'
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const formItemCtx = inject<FormItemContext>(FormItemKey)!;
    const { type } = props;
    const onInput = (event: Event): void => {
      const value = (event.target as HTMLInputElement).value;
      if (value !== props.modelValue) {
        emit('update:modelValue', value);
      }
    };
    const onBlur = (): void => {
      formItemCtx.handlerControlBlur!(props.modelValue);
    };

    watch(() => props.modelValue, val => {
      formItemCtx.handlerValueChange!(val);
    });


    return () => {
      return (
        <div class="ant-field-wrap">
          <input
            type = { type }
            class = "ant-field"
            value = { props.modelValue }
            onInput = { onInput }
            onBlur = { onBlur }
          />
        </div>
      );
    }
  }
});
